package com.example.lin.handlermessage;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {
    ProgressBar bar = null;
    Button startButton = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        bar = (ProgressBar)findViewById(R.id.bar);
        startButton = (Button)findViewById(R.id.startButton);
        startButton.setOnClickListener(new ButtonListener());
    }

    class ButtonListener implements OnClickListener{
        public void onClick(View v){
            bar.setVisibility(View.VISIBLE);
            updateBarHandler.post(updateThread);
        }


    }
    Handler updateBarHandler = new Handler(){
        public void handleMessage(Message msg){
            bar.setProgress(msg.arg1);
            //进度条自动更新
            updateBarHandler.post(updateThread);
        }
    };
    Runnable updateThread = new Runnable() {
        int i = 0;
        @Override
        public void run() {

                System.out.println("Begin Thread");
                i = i + 10;
                Message msg = updateBarHandler.obtainMessage();
                msg.arg1 = i;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                updateBarHandler.sendMessage(msg);

            if ( i == 100){
                updateBarHandler.removeCallbacks(updateThread);
                bar.setVisibility(View.GONE);
            }

        }
    };
}
